package com.nwpu.coursesupport.tool;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UpdateUtil {
	public static int setValues(Object to, Object from){
		if (to == null || from == null){
			return 0;
		}
		int count = 0;
		List<Field> fields=getFields(to.getClass(),true);//获得所有的public属性
		for (Field f : fields){
			try {
				Field fromField=getField(from.getClass(),f.getName(),true);
				Object fromValue=getValue(fromField,from);
				if (fromValue == null){
					continue;
				}
				Object toValue = getValue(f,to);
				if (toValue!=null&&toValue.equals(fromValue)){
					continue;
				}
				setField(f,to, fromValue);
				count += 1;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return count;
	}
	
	private static List<Field> getFields(Class _class,boolean flag){
		Field [] fields=_class.getDeclaredFields();
		List<Field> result=null;
		if(flag&&_class.getSuperclass()!=null){
			result=getFields(_class.getSuperclass(),true);
		}
		if(result==null){
			result=new ArrayList<Field>();
		}
		result.addAll(Arrays.asList(fields));
		return result;
	}
	
	private  static Field getField(Class _class,String name,boolean flag){
		Field [] fields=_class.getDeclaredFields();
		for(Field f : fields){
			if(f.getName().equals(name)){
				return f;
			}
		}
		if(flag&&_class.getSuperclass()!=null){
			return getField(_class.getSuperclass(),name,true);
		}
		return null;
	}
	
	private static void setField(Field f,Object obj,Object value) throws IllegalArgumentException, IllegalAccessException{
		f.setAccessible(true);
		f.set(obj, value);
	}
	
	private static Object getValue(Field f,Object obj) throws IllegalArgumentException, IllegalAccessException{
		if(f==null)
			return null;
		f.setAccessible(true);
		return f.get(obj);
	}
	
}
